import React, {Component} from 'react'
import { Table, Button, Checkbox, Icon, Select, Modal, message } from 'antd'
import moment from 'moment'
import update from 'react-addons-update'
import { IntentionChoice, StudentDetail, OrderRecord, CommunicateRecord } from './'
import { myFetch } from '../utils'

const Option = Select.Option

// 意向学员组件
class IntentionStu extends Component {
  constructor() {
    super()
    this.record = {}
    this.orignal = []
    this.previous = []
    this.selectedRowKeys = []
    this.searchRecord = {
      phoneNumber: false,
      keyword: false,
      startAt: false,
      endAt: false,
    }
    this.previousRecord = {...this.searchRecord}
    this.state = {
      startValue: null,
      endValue: null,
      endOpen: false,
      stuVisible: false,
      num: 1,
      data: [], // 表格数据
      sortByIndex: 0,
    }
    this.setStuVisible = this.setStuVisible.bind(this)
    this.modalBtnRender = this.modalBtnRender.bind(this)
    this.fetchCustomers = this.fetchCustomers.bind(this)
    this.closeModal = this.closeModal.bind(this)
    this.removeCustomer = this.removeCustomer.bind(this)
    this.formatCustomerRecord = this.formatCustomerRecord.bind(this)
    this.filterTable = this.filterTable.bind(this)
    this.batchRemove = this.batchRemove.bind(this)
    this.recordSearch = this.recordSearch.bind(this)
    this.sort = this.sort.bind(this)
  }

  setStuVisible(stuVisible) {
    this.setState({ stuVisible })
  }

  closeModal(data = {}) {
    if ('undefined' === typeof data.index) {
      this.setState({stuVisible: false})
      return
    }
    const { common: { levels, types, sources } } = this.props
    const { data: dataState } = this.state
    const { level, genre, source } = data
    let record = Object.assign({}, data)
    record = this.formatCustomerRecord(record)

    const newData = update(dataState, {
      [data.index]: {
        $merge: {
          ...record,
        }
      }
    })
    this.setState({
      data: newData,
      stuVisible: false,
    })
  }

  modalBtnRender(num) {
    const { common } = this.props
    const { data, stuVisible } = this.state
    let result
    switch (num) {
      case 1:
        result = (
          <StudentDetail
            modal={stuVisible}
            closeModal={this.closeModal}
            data={this.record}
            common={common}
            delCallback={(i, _id) => {
              this.removeCustomer(i, _id)
            }}
          />
        )
        break
      case 2:
        result = <OrderRecord />
        break
      case 3:
        result = <CommunicateRecord />
        break
      default:
        result = null
    }
    return result
  }

  componentDidMount() {
    this.fetchCustomers()
  }

  render() {
    const { common } = this.props
    const { num, data, sortByIndex } = this.state
    const columns = [{
      title: '手机号',
      dataIndex: 'phoneNumber',
      render: text => {
        return <span>{text ? `${text.substr(0, 3)}****${text.slice(-4)}` : null}</span>
      }
    }, {
      title: '姓名',
      dataIndex: 'name',
    }, {
      title: '需求',
      dataIndex: 'demand',
    }, {
      title: '客户级别',
      dataIndex: 'level',
      render: text => {
        return <span className="rt-color-yellow">{text ? text.name : ''}</span>
      }
    }, {
      title: '创建日期',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: text => {
        if (!text) return null
        return <span>{moment(text).format('YYYY-MM-DD')}</span>
      }
    }, {
      title: '负责人',
      dataIndex: 'manager',
      render: text => {
        if (text && text.length > 0) {
          const arr = text.map(v => v.username)
          return <span>{arr.join(',')}</span>
        }
        return ''
      }
    }, {
      title: '下次沟通',
      dataIndex: 'nextAt',
      render: text => {
        if (!text) return null
        return <span>{moment(text).format('YYYY-MM-DD')}</span>
      }
    }, {
      title: '操作',
      dataIndex: 'uilty',
      render: (text, record, index) => {
        return (
          <div className="rt-operation">
            <Button
              icon="edit"
              onClick={() => {
                  record.index = index
                  this.record = record
                  this.setState({
                    stuVisible: true,
                  })
                }
              }
            >
              编辑
            </Button>
            <Button icon="exception">订单</Button>
            <Icon
              type="delete"
              className="rt-color-red"
              onClick={() => {
                Modal.confirm({
                  content: '确定执行删除操作吗？',
                  onOk: () => {
                    this.removeCustomer(index, record._id)
                  }
                })
              }}
            />
          </div>
        )
      }
    }]
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.selectedRowKeys = selectedRowKeys
      },
      onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows)
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows)
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User',    // Column configuration not to be checked
      }),
    }
    return (
        <div className="rt-intention">
          <header className="rt-customer-header cl">
            <h3 className="lf rt-prop-title">意向学员</h3>
            <ul className="rt-stu-title">
              <li>
                <strong className="rt-color-pureBlue">全部</strong>
                <span>|</span>
              </li>
              <li>
                <strong>我负责的</strong>
                <span>|</span>
              </li>
              <li>
                <strong>今日需要联系的</strong>
                <em className="rt-circle-solid">2</em>
                <span>|</span>
              </li>
              <li>
                <strong>本周需要联系的</strong>
                <span>|</span>
              </li>
              <li>
                <strong>最新创建</strong>
                <span>|</span>
              </li>
              <li>
                <strong>无负责人</strong>
              </li>
            </ul>
            <ul className="rt-stu-title">
              {
                ['按沟通时间排序', '按创建日期排序', '按负责人排序', '按客户级别排序'].map((v, i) => (
                  <li
                    key={i}
                    onClick={() => this.sort(i)}
                  >
                    <strong className={`${sortByIndex === i ? 'rt-color-pureBlue' : ''}`}>{v}</strong>
                    <span>|</span>
                  </li>
                ))
              }
            </ul>
          </header>
          <IntentionChoice
            formatCustomerRecord={data => this.formatCustomerRecord(data)}
            common={common}
            newSuccCb={record => {
              const newData = update(data, {
                $unshift: [record]
              })
              this.setState({
                data: newData,
              })
            }}
            search={(condition) => this.filterTable(condition)}
            batchRemove={this.batchRemove}
          />
          <Table
            rowKey="_id"
            className="rt-itent-table"
            columns={columns}
            dataSource={data}
            rowSelection={rowSelection}
          />
          <Modal
            title="学员详情"
            onCancel={() => this.setStuVisible(false)}
            wrapClassName="vertical-center-modal"
            visible={this.state.stuVisible}
            footer={null}
          >
            <div className="cl ">
              <Button
                className={`${ num == 1 ? 'rt-btn-bottom-active' : null} rt-btn-show  lf`}
                onClick={
                  () => {
                    this.setState({
                      num: 1,
                    })
                  }
                }
              >
                学员详情
              </Button>
              <Button
                className={`${ num == 2 ? 'rt-btn-bottom-active' : null } rt-btn-margin-left rt-btn-show  lf`}
                onClick={
                  () => {
                    this.setState({
                      num: 2,
                    })
                  }
                }
              >
                订单记录
              </Button>
              <Button
                className={`${ num == 3 ? 'rt-btn-bottom-active' : null} rt-btn-margin-left rt-btn-show  lf`}
                onClick={
                  () => {
                    this.setState({
                      num: 3,
                    })
                  }
                }
              >
                沟通记录
              </Button>
              <Button
                className="rt-btn-return rf"
                onClick={
                  () => {
                    this.setStuVisible(false)
                  }
                }
              >
                返回列表
              </Button>
            </div>
            {this.modalBtnRender(num)}
          </Modal>
        </div>
      )
  }
  fetchCustomers() {
    myFetch('/v1/customers')
      .then(rs => {
        if (rs && rs.length > 0) {
          this.orignal = rs
          this.setState({
            data: rs,
          })
        }
      })
  }
  removeCustomer(i, _id) {
    const { data } = this.state
    const newData = update(data, {
      $splice: [[i, 1]]
    })
    myFetch(`/v1/customers/${_id}`, {method: 'DELETE'})
      .then(rs => {
        if (!rs.error) {
          message.success('删除成功')
          this.setState({
            stuVisible: false,
            data: newData,
          })
        }
      })
  }
  formatCustomerRecord(data) {
    const { common: { levels, types, sources } } = this.props
    const { level, genre, source } = data
    if (level) {
      const filteredArr = levels.filter(v => {
        return v._id === level
      })
      if (filteredArr[0]) {
        data.level = filteredArr[0]
      }
    }
    if (genre) {
      const filteredArr = types.filter(v => v._id === genre)
      if (filteredArr[0]) {
        data.genre = filteredArr[0]
      }
    }
    if (source) {
      const filteredArr = sources.filter(v => v._id === source)
      if (filteredArr[0]) {
        data.source = filteredArr[0]
      }
    }
    return data
  }
  filterTable(condition) {
    const { data } = this.state
    this.recordSearch(condition)
    const { phoneNumber, keyword, startAt, endAt } = condition
    if (!phoneNumber && !keyword && !startAt && !endAt) {
      this.setState({
        data: this.orignal,
      })
      return
    }
    let filteredArr = []
    let opArr = []
    if (keyword) {
      filteredArr = data.filter(v => {
        let nameFilter = false
        let genreFilter = false
        let managerFilter = false
        if (v.name) {
          nameFilter = v.name.indexOf(condition.keyword) !== -1
        }
        if (v.level && v.level.name) {
          genreFilter = v.level.name.indexOf(keyword) !== -1
        }
        if (v.manager && v.manager.length > 0) {
          const managers = v.manager.map(v => v.username)
          if (managers.includes(keyword)) {
            managerFilter = true
          }
          else {
            for (let m of managers) {
              if (m && m.indexOf(keyword) !== -1) {
                managerFilter = true
              }
            }
          }
        }
        if (nameFilter || genreFilter || managerFilter) {
          return true
        }
      })
    }
    if (phoneNumber) {
      opArr = (filteredArr.length > 0) ? [...filteredArr] : [...this.orignal]
      filteredArr = opArr.filter(v => v.phoneNumber.indexOf(phoneNumber) !== -1)
    }
    else {
      if (this.previousRecord.phoneNumber === true) {
        filteredArr = [...this.previous]
      }
    }
    if (startAt) {
      opArr = (filteredArr.length > 0) ? [...filteredArr] : [...this.orignal]
      filteredArr = opArr.filter(v => {
        if (moment(v.createdAt).isAfter(startAt)) {
          return true
        }
      })
    }
    else {
      if (this.previousRecord.startAt === true) {
        filteredArr = [...this.previous]
      }
    }
    if (endAt) {
      opArr = (filteredArr.length > 0) ? [...filteredArr] : [...this.orignal]
      filteredArr = opArr.filter(v => {
        if (moment(v.createdAt).isBefore(endAt)) {
          return true
        }
      })
    }
    else {
      if (this.previousRecord.endAt === true) {
        filteredArr = [...this.previous]
      }
    }
    this.setState(prevState => {
      this.previous = [...prevState.data]
      return {
        data: filteredArr,
      }
    })
  }
  batchRemove() {
    const { data } = this.state
    const body = {
      _id: this.selectedRowKeys,
    }
    if (this.selectedRowKeys.length < 1) {
      message.info('请至少选择一项')
      return
    }

    Modal.confirm({
      content: '确定执行批量删除操作吗？',
      onOk: () => {
        myFetch('/v1/customers/batch/delete', {method: 'POST', body: JSON.stringify(body)})
        .then(rs => {
          if (rs && rs.ok == 1) {
            message.success('操作成功')
            const filteredArr = data.filter(v => !this.selectedRowKeys.includes(v._id))
            this.setState({
              data: filteredArr,
            }, () => {
              this.selectedRowKeys = []
            })
          }
        })
      }
    })

  }
  recordSearch({ phoneNumber, keyword, startAt, endAt }) {
    this.previousRecord = {...this.searchRecord}
    this.searchRecord = {
      phoneNumber: phoneNumber ? true : false,
      keyword: keyword ? true : false,
      startAt: startAt ? true : false,
      endAt: endAt ? true : false,
    }
  }
  sort(i) {
    const { sortByIndex, data } = this.state
    if (sortByIndex === i) return
    const opArr = [...data]
    opArr.sort((a, b) => {
      if (i === 0) {
        return moment(a.nextAt).isBefore(b.nextAt)
      }
      else if (i === 1) {
        return moment(a.createdAt).isBefore(b.createdAt)
      }
      else if (i === 2) {
        if (a.manager && a.manager.length > 0) {
          if (b.manager && b.manager.length > 0) {
            if (a.manager[0].username > b.manager[0].username) return 1
            if (a.manager[0].username < b.manager[0].username) return -1
            return 0
          }
          return -1
        }
        if (b.manager && b.manager.length > 0) {
          if (a.manager && a.manager.length > 0) {
            // oppsite of the below
            if (a.manager[0].username > b.manager[0].username) return -1
            if (a.manager[0].username < b.manager[0].username) return 1
            return 0
          }
          // oppsite of the below
          return 1
        }
      }
      else if (i === 3) {
        if (a.level && b.level) {
          if (a.level.name > b.level.name) return -1
          if (a.level.name < b.level.name) return 1
        }
        return 0
      }
    })
    this.setState({sortByIndex: i, data: opArr})
  }
}

export default IntentionStu